package com.iamteer.cupband;

import android.app.Activity;
import android.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.Timer;
import java.util.TimerTask;


public class BondingFragment extends Fragment {

//    static byte waterLevelBack;
    private Button btnSubmit;
    private ImageView ivWaterLevel;
//    private ComputeAngle computeAngle = new ComputeAngle();
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_bonding, container, false);

        btnSubmit = (Button) root.findViewById(R.id.btnSubmit);
        ivWaterLevel = (ImageView) root.findViewById(R.id.ivWaterLevel);

        if(MainActivity.mState == MainActivity.UART_PROFILE_CONNECTED){
            btnSubmit.setEnabled(false);
            btnSubmit.setAlpha(0.4f);
            ivWaterLevel.setAlpha(0.4f);
        }

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.mBtAdapter = BluetoothAdapter.getDefaultAdapter();

                if(MainActivity.mBtAdapter == null){
                    Toast.makeText(getActivity(), "Bluetooth is not availabe", Toast.LENGTH_LONG).show();
                    BondingActivity.bondingActivity.finish();
                    return;
                }
                serviceInit();

                if (!MainActivity.mBtAdapter.isEnabled()) {
                    Log.i(MainActivity.TAG, "onClick - BT not enabled yet");
                    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableIntent, MainActivity.REQUEST_ENABLE_BT);
                } else {
                    //Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices
                    Intent newIntent = new Intent(getActivity(), DeviceListActivity.class);
                    startActivityForResult(newIntent, MainActivity.REQUEST_SELECT_DEVICE);
                }
            }
        });


        return root;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(MainActivity.TAG, "... onActivityResultdevice ...");
        switch (requestCode) {

            case MainActivity.REQUEST_SELECT_DEVICE:
                //When the DeviceListActivity return, with the selected device address
                if (resultCode == Activity.RESULT_OK && data != null) {
                    String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
                    MainActivity.mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);

                    Log.d(MainActivity.TAG, "... onActivityResultdevice.address==" + MainActivity.mDevice + " mserviceValue: " + MainActivity.mService);

                    Toast.makeText(getActivity(), "正在连接设备", Toast.LENGTH_SHORT).show();
                    if(MainActivity.mService.connect(deviceAddress)){
                        Timer timer = new Timer();
                        TimerTask startNewFragment = new TimerTask() {
                            @Override
                            public void run() {
                                getFragmentManager().beginTransaction()
                                        .replace(R.id.fragment, new BondingAfterFragment())
                                        .commit();
                            }
                        };
                        timer.schedule(startNewFragment, 1000);

                        TimerTask finishActivity = new TimerTask() {
                            @Override
                            public void run() {
                                BondingActivity.bondingActivity.finish();
                            }
                        };
                        timer.schedule(finishActivity, 3000);
                    }
                }
                break;
            case MainActivity.REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    Toast.makeText(getActivity(), "Bluetooth has turned on ", Toast.LENGTH_SHORT).show();

                } else {
                    // User did not enable Bluetooth or an error occurred
                    Log.d(MainActivity.TAG, "BT not enabled");
                    Toast.makeText(getActivity(), "Problem in BT Turning ON ", Toast.LENGTH_SHORT).show();
                    getActivity().finish();
                }
                break;
            default:
                Log.e(MainActivity.TAG, "wrong request code");
                break;
        }
    }


//    private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {
//
//        public void onReceive(Context context, Intent intent) {
//            String action = intent.getAction();
//
//            final Intent mIntent = intent;
//            //final String Test;
//            //*********************//
//            if (action.equals(UartService.ACTION_GATT_CONNECTED)) {
//                getActivity().runOnUiThread(new Runnable() {
//                    public void run() {
//                        String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
//                        Log.d(MainActivity.TAG, "UART_CONNECT_MSG");
//                        MainActivity.mState = MainActivity.UART_PROFILE_CONNECTED;
//                    }
//                });
//            }
//
//            //*********************//
//            if (action.equals(UartService.ACTION_GATT_DISCONNECTED)) {
//                getActivity().runOnUiThread(new Runnable() {
//                    public void run() {
//                        Log.d(MainActivity.TAG, "UART_DISCONNECT_MSG");
//
//                        MainActivity.mState = MainActivity.UART_PROFILE_DISCONNECTED;
//                        //MainActivity.mService.close();
//                    }
//                });
//            }
//
//
//            //*********************//
//            if (action.equals(UartService.ACTION_GATT_SERVICES_DISCOVERED)) {
//                MainActivity.mService.enableTXNotification();
//            }
//            //*********************//
//            if (action.equals(UartService.ACTION_DATA_AVAILABLE)) {
//                final String rxStr = computeAngle.setRawData(intent.getByteArrayExtra(UartService.EXTRA_DATA));
//                final short x, y, z;
//                final float xf, yf, zf;
//                final double waterlevel;
////                byte[] data = new byte[1];
//                x = computeAngle.getAcceleration().x;
//                y = computeAngle.getAcceleration().y;
//                z = computeAngle.getAcceleration().z;
//
//                xf = x/256f;
//                yf = y/256f;
//                zf = z/256f;
//
//                waterlevel = -y / Math.sqrt(y*y + z*z);
//                MainActivity.waterLeft = (int) ( 100 * waterlevel );
////                data[0] = (byte) ((MainActivity.waterLeft+5)/10);
////                MainActivity.mService.writeRXCharacteristic(data);
//                if(MainActivity.waterLeft <= 0  && computeAngle.getLastLevel() > 0){
//                    MainActivity.result++;
//                    System.out.println("杯数：" + MainActivity.result);
//                }
//                MainActivity.mainActivity.runOnUiThread(new Runnable() {
//                    public void run() {
//                        try {
////                            textView.setText("倾角：" + String.valueOf(MainActivity.waterLeft));
////                            System.out.println("倾角：" + String.valueOf(computeAngle.getAngle(z, y)));
//                            System.out.println(String.format("Water Left: %f   %d%%    %s", waterlevel, MainActivity.waterLeft, rxStr));
//
//                        } catch (Exception e) {
//                            Log.e("Error", e.toString());
//                        }
//                    }
//                });
//
//
//
//            }
//            //*********************//
//            if (action.equals(UartService.DEVICE_DOES_NOT_SUPPORT_UART)) {
////                Log.i(MainActivity.TAG, "Device doesn't support UART. Disconnecting");
//                Toast.makeText(getActivity(), "Device doesn't support UART. Disconnecting", Toast.LENGTH_SHORT).show();
//                MainActivity.mService.disconnect();
//            }
//        }
//    };



    public ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder rawBinder) {
            MainActivity.mService = ((UartService.LocalBinder) rawBinder).getService();
            Log.d(MainActivity.TAG, "onServiceConnected mService = " + MainActivity.mService);
            if(!MainActivity.mService.initialize()){
                Log.e(MainActivity.TAG, "Unable to initialize Bluetooth");
                getActivity().finish();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            MainActivity.mService.close();
            MainActivity.mService = null;
        }
    };

    private void serviceInit() {
        Intent bindIntent = new Intent(getActivity(), UartService.class);
        MainActivity.mainActivity.bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
//        LocalBroadcastManager.getInstance(MainActivity.mainActivity).registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
    }

//    private static IntentFilter makeGattUpdateIntentFilter() {
//        final IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(UartService.ACTION_GATT_CONNECTED);
//        intentFilter.addAction(UartService.ACTION_GATT_DISCONNECTED);
//        intentFilter.addAction(UartService.ACTION_GATT_SERVICES_DISCOVERED);
//        intentFilter.addAction(UartService.ACTION_DATA_AVAILABLE);
//        intentFilter.addAction(UartService.DEVICE_DOES_NOT_SUPPORT_UART);
//        return intentFilter;
//    }

}



